// 积分页面逻辑
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentPoints: '1,258',
    todayPoints: '+120',
    totalEarned: '3,450',
    totalSpent: '2,192',
    tasks: [
      {
        id: 1,
        title: '每日签到',
        desc: '连续签到奖励更多',
        reward: '+10',
        icon: '⏰',
        iconClass: 'checkin',
        completed: true,
        progress: 100,
        maxProgress: 100
      },
      {
        id: 2,
        title: '完成学习计划',
        desc: '今日已完成 2/3',
        reward: '+30',
        icon: '📚',
        iconClass: 'study',
        completed: false,
        progress: 2,
        maxProgress: 3
      },
      {
        id: 3,
        title: '分享学习成果',
        desc: '分享到社交平台',
        reward: '+20',
        icon: '💎',
        iconClass: 'share',
        completed: false,
        progress: 0,
        maxProgress: 1
      },
      {
        id: 4,
        title: '邀请好友',
        desc: '每邀请1位+50积分',
        reward: '+50',
        icon: '👥',
        iconClass: 'invite',
        completed: false,
        progress: 1,
        maxProgress: 3
      },
      {
        id: 5,
        title: '学习时长达标',
        desc: '今日学习满2小时',
        reward: '+25',
        icon: '⏱️',
        iconClass: 'time',
        completed: true,
        progress: 120,
        maxProgress: 120
      },
      {
        id: 6,
        title: '完成匹配学习',
        desc: '与伙伴一起学习',
        reward: '+40',
        icon: '🤝',
        iconClass: 'match',
        completed: false,
        progress: 0,
        maxProgress: 1
      }
    ],
    pointsHistory: [
      {
        id: 1,
        type: 'earn',
        title: '每日签到',
        points: 10,
        time: '今天 08:30',
        icon: '⏰'
      },
      {
        id: 2,
        type: 'earn',
        title: '学习时长达标',
        points: 25,
        time: '今天 10:15',
        icon: '⏱️'
      },
      {
        id: 3,
        type: 'spend',
        title: '兑换学习资料',
        points: -50,
        time: '昨天 16:20',
        icon: '📖'
      },
      {
        id: 4,
        type: 'earn',
        title: '完成匹配学习',
        points: 40,
        time: '昨天 14:30',
        icon: '🤝'
      }
    ],
    showMessage: false,
    messageText: '',
    messageType: 'success'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('积分页面加载');
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 加载积分数据
    this.loadPointsData();
    
    // 加载任务数据
    this.loadTasksData();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('local_token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      wx.navigateTo({
        url: '/subpkg/pages/login/login'
      });
      return false;
    }
    return true;
  },
  
  // 加载积分数据 - 模拟版本
  async loadPointsData() {
    const token = wx.getStorageSync('local_token');
    if (!token) return;
    
    try {
      // 模拟延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 模拟积分数据
      const mockPointsData = {
        current_points: 850,
        today_earned: 45,
        total_earned: 1250,
        total_spent: 400
      };
      
      this.setData({
        currentPoints: mockPointsData.current_points,
        todayPoints: mockPointsData.today_earned,
        totalEarned: mockPointsData.total_earned,
        totalSpent: mockPointsData.total_spent
      });
    } catch (error) {
      console.error('加载积分数据失败:', error);
      // 使用默认数据
      this.setData({
        currentPoints: 850,
        todayPoints: 45,
        totalEarned: 1250,
        totalSpent: 400
      });
    }
  },

  // 加载任务数据 - 模拟版本
  async loadTasksData() {
    const token = wx.getStorageSync('local_token');
    if (!token) return;
    
    try {
      // 模拟延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 模拟任务数据
      const mockTasksData = [
        {
          id: 1,
          name: '每日登录',
          description: '每日首次打开小程序',
          reward_points: 5,
          task_type: 'daily_login',
          user_completion: { completed: true, progress: 1 },
          completion_condition: 1
        },
        {
          id: 2,
          name: '专注学习30分钟',
          description: '单次专注学习30分钟以上',
          reward_points: 10,
          task_type: 'study_duration',
          user_completion: { completed: false, progress: 0 },
          completion_condition: 1
        },
        {
          id: 3,
          name: '完成学习会话',
          description: '完成一次完整的学习会话',
          reward_points: 15,
          task_type: 'complete_session',
          user_completion: { completed: true, progress: 1 },
          completion_condition: 1
        },
        {
          id: 4,
          name: '鼓励学习伙伴',
          description: '向学习伙伴发送鼓励',
          reward_points: 3,
          task_type: 'encourage_friend',
          user_completion: { completed: false, progress: 0 },
          completion_condition: 1
        },
        {
          id: 5,
          name: '连续学习7天',
          description: '连续7天完成学习会话',
          reward_points: 50,
          task_type: 'continuous_days',
          user_completion: { completed: false, progress: 3 },
          completion_condition: 7
        }
      ];
      
      const formattedTasks = mockTasksData.map(task => ({
        id: task.id,
        title: task.name,
        desc: task.description,
        reward: task.reward_points,
        icon: this.getTaskIcon(task.task_type),
        iconClass: this.getTaskIconClass(task.task_type),
        completed: task.user_completion?.completed || false,
        progress: task.user_completion?.progress || 0,
        target: task.completion_condition || 1
      }));
      
      this.setData({
        tasks: formattedTasks
      });
    } catch (error) {
      console.error('加载任务数据失败:', error);
      // 使用默认任务数据
      this.setData({
        tasks: [
          {
            id: 1,
            title: '每日登录',
            desc: '每日首次打开小程序',
            reward: 5,
            icon: '📅',
            iconClass: 'task-icon-blue',
            completed: true,
            progress: 1,
            target: 1
          },
          {
            id: 2,
            title: '专注学习30分钟',
            desc: '单次专注学习30分钟以上',
            reward: 10,
            icon: '⏰',
            iconClass: 'task-icon-green',
            completed: false,
            progress: 0,
            target: 1
          },
          {
            id: 3,
            title: '完成学习会话',
            desc: '完成一次完整的学习会话',
            reward: 15,
            icon: '✅',
            iconClass: 'task-icon-orange',
            completed: true,
            progress: 1,
            target: 1
          },
          {
            id: 4,
            title: '鼓励学习伙伴',
            desc: '向学习伙伴发送鼓励',
            reward: 3,
            icon: '👏',
            iconClass: 'task-icon-purple',
            completed: false,
            progress: 0,
            target: 1
          },
          {
            id: 5,
            title: '连续学习7天',
            desc: '连续7天完成学习会话',
            reward: 50,
            icon: '🔥',
            iconClass: 'task-icon-red',
            completed: false,
            progress: 3,
            target: 7
          }
        ]
      });
    }
  },
  
  // 获取任务图标
  getTaskIcon(taskType) {
    const iconMap = {
      'daily_login': '📅',
      'study_duration': '⏰',
      'complete_session': '✅',
      'encourage_friend': '👏',
      'continuous_days': '🔥'
    };
    return iconMap[taskType] || '🎯';
  },
  
  // 获取任务图标样式
  getTaskIconClass(taskType) {
    const classMap = {
      'daily_login': 'task-icon-blue',
      'study_duration': 'task-icon-green',
      'complete_session': 'task-icon-orange',
      'encourage_friend': 'task-icon-purple',
      'continuous_days': 'task-icon-red'
    };
    return classMap[taskType] || 'task-icon-default';
  },

  /**
   * 跳转到积分详情页
   */
  goToPointsDetail() {
    wx.navigateTo({
      url: '/pages/points-detail/points-detail'
    });
  },
  
  // 刷新数据
  onRefresh() {
    this.loadPointsData();
    this.loadTasksData();
  },

  /**
   * 查看全部任务
   */
  viewAllTasks() {
    console.log('查看全部任务');
  },

  /**
   * 完成任务 - 模拟版本
   */
  async completeTask(e) {
    const taskId = e.currentTarget.dataset.id;
    const token = wx.getStorageSync('local_token');
    
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    const taskIndex = this.data.tasks.findIndex(task => task.id === taskId);
    if (taskIndex === -1 || this.data.tasks[taskIndex].completed) {
      return;
    }
    
    try {
      // 模拟延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 模拟成功响应
      const mockResponse = { success: true };
      
      if (mockResponse.success) {
        // 更新任务状态
        const updatedTasks = [...this.data.tasks];
        updatedTasks[taskIndex].completed = true;
        
        // 更新积分
        const reward = updatedTasks[taskIndex].reward;
        const newCurrentPoints = this.data.currentPoints + reward;
        const newTodayPoints = this.data.todayPoints + reward;
        const newTotalEarned = this.data.totalEarned + reward;
        
        this.setData({
          tasks: updatedTasks,
          currentPoints: newCurrentPoints,
          todayPoints: newTodayPoints,
          totalEarned: newTotalEarned
        });
        
        wx.showToast({
          title: `获得 ${reward} 积分！`,
          icon: 'success',
          duration: 2000
        });
      } else {
        throw new Error('完成任务失败');
      }
    } catch (error) {
      console.error('完成任务失败:', error);
      wx.showToast({
        title: '完成任务失败',
        icon: 'none'
      });
    }
  },

  /**
   * 显示消息提示
   */
  showMessage(message, type = 'success') {
    this.setData({
      showMessage: true,
      messageText: message,
      messageType: type
    });
    
    // 3秒后自动隐藏
    setTimeout(() => {
      this.setData({
        showMessage: false
      });
    }, 3000);
  },

  /**
   * Tab切换处理
   */
  onTabSwitch(e) {
    console.log('Tab切换:', e.detail);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log('积分页面渲染完成');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('积分页面显示');
    this.onRefresh();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log('积分页面隐藏');
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('积分页面卸载');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    console.log('下拉刷新');
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('上拉触底');
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '督搭 - 学习监督小程序',
      path: '/pages/index/index'
    };
  }
});
